import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import { setToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
})

//request interceptor
service.interceptors.request.use(
    config => {

        if (store.getters.token) {
            config.headers.Authorization = "Bearer " + store.getters.token
        }
        return config
    },
    error => {
        // do something with request error
        return Promise.reject(error)
    }
)

//response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data
        if(response.headers.Authorization){
            setToken(response.headers.Authorization)
        }
        if (res.code != 200) {
            if (res.code === 401) {
                store.dispatch("user/outLogin").then(() => {
                    location.reload()
                });
            }
            Message({
                message: res.msg || 'Error',
                type: 'error',
                duration: 2 * 1000
            })
            return Promise.reject(new Error(res.msg || 'Error'))
        } else {
            return res
        }
    },
    error => {
        Message({
            message: error,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(new Error('Error'))
    }
)
export default service